package com.ingenico.piccolo.nodes;

import java.awt.Dimension;
import java.awt.geom.AffineTransform;

import edu.umd.cs.piccolo.PCanvas;
import edu.umd.cs.piccolo.activities.PActivity;
import edu.umd.cs.piccolo.activities.PInterpolatingActivity;
import edu.umd.cs.piccolo.activities.PTransformActivity;
import edu.umd.cs.piccolo.nodes.PText;
import edu.umd.cs.piccolo.util.PAffineTransform;
import edu.umd.cs.piccolo.util.PUtil;

public class PAboutCanvas extends PCanvas {
	/**
	 * Generated Serial Version UID
	 */
	private static final long serialVersionUID = -794498983957405975L;

	public final static int CANVAS_WIDTH = 320;
	public final static int CANVAS_HEIGHT = 150;

	private final String[] messages;

	private final PText text;

	private final PTransformActivity.Target target = new PTransformActivity.Target() {
		public void setTransform(AffineTransform aTransform) {
			text.setTransform(aTransform);
		}

		public void getSourceMatrix(double[] aSource) {
			text.getTransformReference(true).getMatrix(aSource);
		}
	};

	private PTransformActivity ta = null;

	public void initActivity() {
		ta = new PTransformActivity(5000, PUtil.DEFAULT_ACTIVITY_STEP_RATE, Integer.MAX_VALUE, PInterpolatingActivity.SOURCE_TO_DESTINATION, target, null) {
			int currentIndex = 0;

			@Override
			public boolean getFirstLoop() {
				// Hack to force re-computation of the source transform...
				return true;
			}

			@Override
			protected void activityStarted() {
				text.setText(messages[(currentIndex++)%messages.length]);
				text.setOffset(0, 0);
				text.setRotation(1.7);
				text.setScale(0.5);
				double dx = (CANVAS_WIDTH / 1.2) - text.getBounds().getCenterX();
				double dy = CANVAS_HEIGHT;//(CANVAS_HEIGHT / 1.3) - text.getBounds().getCenterY();
				text.offset(dx, dy);

				double scale = CANVAS_WIDTH / (text.getBounds().getWidth());
				PAffineTransform destTransform = text.getTransform();
				destTransform.setOffset(0, -(text.getBounds().getHeight()*scale));
				destTransform.setScale(scale);
				destTransform.setRotation(0);

				double[] matrix = new double[6];
				destTransform.getMatrix(matrix);
				setDestinationTransform(matrix);

				super.activityStarted();
			}
		};
		text.addActivity(ta);
	}
	public void shutdownActivity() {
		ta.terminate(PActivity.TERMINATE_WITHOUT_FINISHING);
		ta = null;
	}

    private void initDialog() {
    	getLayer().addChild(text);
		setSize(CANVAS_WIDTH, CANVAS_HEIGHT);
		setPreferredSize(new Dimension(CANVAS_WIDTH,CANVAS_HEIGHT));
		// remove Pan and Zoom
		removeInputEventListener(getPanEventHandler());
		removeInputEventListener(getZoomEventHandler());
    }

	public PAboutCanvas(String[] messages) {
		text = new PText();
		this.messages = messages;
        initDialog();
	}
}
